package com.lzy.chat.e_util;

import com.lzy.chat.c_service.Exception.Exceptions;
import com.lzy.chat.c_service.Exception.ServiceException;
import org.apache.http.HttpResponse;
import org.springframework.mail.SimpleMailMessage;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;


public class GetCode {

    public static SimpleMailMessage sendMail(String to, String code) throws UnsupportedEncodingException, AddressException {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(new InternetAddress(MimeUtility.encodeText("缩话") + "<1159756729@qq.com>").toString());
        simpleMailMessage.setSubject("验证码");
        String message = "【缩话】 您的验证码是" + code + "，5分钟内有效。如非本人操作，请忽略此邮件";
        simpleMailMessage.setText(message);
        simpleMailMessage.setTo(to);
        return simpleMailMessage;
    }

    public static void sendMessage(String to, String code) {
        String host = "https://gyytz.market.alicloudapi.com";
        String path = "/sms/smsSend";
        String method = "POST";
        String appcode = "0912e390758b4686a013d9b350ccc8e1";
        Map<String, String> headers = new HashMap<>();

        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<>();
        querys.put("mobile", to);
        querys.put("param", "**code**:" + code);
        querys.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
        querys.put("templateId", "63698e3463bd490dbc3edc46a20c55f5");
        Map<String, String> bodys = new HashMap<>();
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            // System.out.println(response.toString());
        } catch (Exception e) {
            System.out.println("错误");
            throw new ServiceException(Exceptions.SendCodeException);
        }
    }

    /**
     * 通过StringBuilder构建一个字符串，用random函数生成6次，生成一个6位数字验证码
     *
     * @return 返回六位数字验证码
     */
    public static String getVerifyCode() {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int num = (int) (Math.random() * 10);
            str.append(num);
        }
        return str.toString();
    }

}
